package main

import (
    "bufio"
    "encoding/binary"
    "fmt"
    "log"
    "math/rand"
    "net"
    "strings"
    "time"
)

// Simple external ACS stub server: on each connection, read one line (sid|B=...),
// then respond: uint32 count, then for each: uint32 len, payload bytes.
// Payloads are 250-byte random transactions. Count defaults to 1000, or parsed from B.

func handleConn(c net.Conn) {
    defer c.Close()
    c.SetDeadline(time.Now().Add(10 * time.Second))
    r := bufio.NewReader(c)
    line, _ := r.ReadString('\n')
    line = strings.TrimSpace(line)
    log.Printf("ACS stub: request sid=%q", line)

    count := 1000
    // parse optional B=
    if idx := strings.Index(line, "B="); idx >= 0 {
        var v int
        if _, err := fmt.Sscanf(line[idx:], "B=%d", &v); err == nil && v > 0 { count = v }
    }
    if err := binary.Write(c, binary.BigEndian, uint32(count)); err != nil {
        log.Printf("write count err: %v", err)
        return
    }
    for i := 0; i < count; i++ {
        size := 250
        if err := binary.Write(c, binary.BigEndian, uint32(size)); err != nil {
            log.Printf("write len err: %v", err)
            return
        }
        buf := make([]byte, size)
        if _, err := rand.Read(buf); err != nil {
            log.Printf("rand read err: %v", err)
            return
        }
        if _, err := c.Write(buf); err != nil {
            log.Printf("write payload err: %v", err)
            return
        }
    }
}

func main() {
    addr := "127.0.0.1:19001"
    ln, err := net.Listen("tcp", addr)
    if err != nil {
        log.Fatalf("listen %s failed: %v", addr, err)
    }
    log.Printf("ACS stub server listening at %s", addr)
    for {
        conn, err := ln.Accept()
        if err != nil {
            log.Printf("accept err: %v", err)
            continue
        }
        go handleConn(conn)
    }
}


